import { Injectable } from '@angular/core';
// 引入Http
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/toPromise';
// 引入根目录、地址栏，这里会报错，因为还没有建立app.config这个文件
import { AppConfig } from '../../app/app.config';
@Injectable()
export //声明可以被注入

class HttpServiceProvider {
    private rootUrl: string; // 声明公共根目录

    constructor(public http: Http) {
        this.rootUrl = AppConfig.appUrl();
    }

    // 声明get方法
    public get(url: string, paramObj: any) {
        // 拼接字符串
        return this.http
            .get(url + this.toQueryString(paramObj))
            .toPromise()
            .then((res) => this.handleSuccess(res.json()))
            .catch((error) => this.handleError(error));
    }
    // 声明post方法
    public post(url: string, paramObj: any) {
        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        return this.http
            .post(url, this.toBodyString(paramObj), new RequestOptions({ headers: headers }))
            .toPromise()
            .then((res) => this.handleSuccess(res.json()))
            .catch((error) => this.handleError(error));
    }
    public postBody(url: string, paramObj: any) {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        return this.http
            .post(url, paramObj, new RequestOptions({ headers: headers }))
            .toPromise()
            .then((res) => this.handleSuccess(res.json()))
            .catch((error) => this.handleError(error));
    }
    private handleSuccess(result) {
        if (result && !result.success) {
            //由于和后台约定好,所有请求均返回一个包含success,msg,data三个属性的对象,所以这里可以这样处理
            // console.log(result.msg);//这里使用ToastController
        }
        return result;
    }
    private handleError(error: Response | any) {
        let msg = '请求失败';
        if (error.status == 0) {
            msg = '请求地址错误';
        }
        if (error.status == 400) {
            msg = '请求无效';
            console.log('请检查参数类型是否匹配');
        }
        if (error.status == 404) {
            msg = '请求资源不存在';
            console.error(msg + '，请检查路径是否正确');
        }
        console.log(error);
        console.log(msg); //这里使用ToastController
        return { success: false, msg: msg };
    }
    private toBodyString(obj) {
        let ret = [];
        for (let key in obj) {
            key = encodeURIComponent(key);
            let values = obj[key];
            if (values && values.constructor == Array) {
                //数组
                let queryValues = [];
                for (let i = 0, len = values.length, value; i < len; i++) {
                    value = values[i];
                    queryValues.push(this.toQueryPair(key, value));
                }
                ret = ret.concat(queryValues);
            } else {
                //字符串
                ret.push(this.toQueryPair(key, values));
            }
        }
        return ret.join('&');
    }
    private toQueryPair(key, value) {
        if (typeof value == 'undefined') {
            return key;
        }
        return key + '=' + encodeURIComponent(value === null ? '' : String(value));
    }

    private toQueryString(obj) {
        if (obj == null) {
            return '';
        }
        let ret = [];
        for (let key in obj) {
            key = encodeURIComponent(key);
            let values = obj[key];
            if (values && values.constructor == Array) {
                //数组
                let queryValues = [];
                for (let i = 0, len = values.length, value; i < len; i++) {
                    value = values[i];
                    queryValues.push(this.toQueryPair(key, value));
                }
                ret = ret.concat(queryValues);
            } else {
                //字符串
                ret.push(this.toQueryPair(key, values));
            }
        }
        return '&' + ret.join('&');
    }

    goLogin(paramObj) {//登录
        return this.post(this.rootUrl + '/api/login/login', paramObj);
    }
}
